from django.shortcuts import render

# Create your views here.
from django.views import View
from django import http
from django_redis import get_redis_connection
from django.http import HttpResponse, JsonResponse
import random, logging

from . import constants
from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.apps.verification.libs.yuntongxun.SendMessage import CCP
from meiduo_mall.apps.verification.libs.captcha.captcha import captcha
from celery_task.sms.tasks import celery_send_sms

logger = logging.getLogger('django')


class SmsCodeView(View):
    def get(self, request, mobile):
        uuid = request.GET.get('uuid')
        image_code_client = request.GET.get('image_code')
        if not all([uuid, image_code_client]):
            return http.HttpResponseForbidden("缺少必填参数")

        redis_conn = get_redis_connection("verify_code")
        # 防止频繁发送短信
        sms_send_count = redis_conn.get('sms_send%s' % mobile)
        if sms_send_count:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})
        # 获取服务器的图片验证码
        image_code_server = redis_conn.get('img_%s' % uuid)
        if image_code_server is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图片验证码已失效'})
        redis_conn.delete('img_%s' % uuid)  # 删除服务器的验证码
        image_code_server = image_code_server.decode()  # 将bytes转换为字符串
        if image_code_server.lower() != image_code_client.lower():  # 转换为小写再比较
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图片验证码错误'})

        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info('手机号短信验证码%s:%s' % (mobile, sms_code))  # 手动输出日志
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        # redis_conn.setex('sms_send%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)  # 做一个标记，是否60s内发送了短信

        # 创建一个redis管道
        pl = redis_conn.pipeline()
        # 将命令添加到管道里面
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_send%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 执行
        pl.execute()

        # CCP().send_msg(constants.SEND_SMS_TEMPLATE_ID, mobile, (sms_code, constants.SMS_CODE_REDIS_EXPIRES // 60))
        # 使用celery异步发送短信
        # send_sms(mobile, sms_code) 错误的写法
        celery_send_sms.delay(mobile, sms_code)

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信成功'})


class ImageView(View):
    def get(self, request, uuid):
        """
        :param request:
        :param uuid: 用来标识哪个用户的验证码
        :return: image/jpg
        """
        text, image = captcha.generate_captcha()
        # 保存到redis
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % uuid, constants.IMAGE_CODE_REDIS_EXPIRES, text)  # 存储并设置过期时间
        return HttpResponse(image, content_type='image/jpeg')
